import time
from datetime import datetime,timedelta
import requests
import json
import time

class task():
    def __init__(self):
        self.upmsurl='https://dxuas.wehdz.gov.cn:30698' #预生产
        self.uverurl = 'https://dxuas.wehdz.gov.cn:32722' #预生产
        self.wlwurl = 'https://dxuas.wehdz.gov.cn:32728' #预生产
        self.ziyuan='https://dxuas.wehdz.gov.cn:32749'#预生产
        self.omc = 'https://dxuas.wehdz.gov.cn:32238'  # 预生产
        self.work='https://dxuas.wehdz.gov.cn:32243' # 预生产
        self.UserAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'


    def login(self,username,password):
        '''统一门户登录'''
        url = self.upmsurl+"/gdu-unified-portal-api/auth/oauth2/token?grant_type=password&username="+username+"&scope=server&randomStr=blockPuzzle&code=EZXohniJiQstVhIQEblJpHsVVP33VvQd6pzO5jAq%2FSl0QoZyRWu3JwYM0190WGWPjX6yWtKwsHPTbaMB0HXqzg%3D%3D"
        payload='password='+password
        headers = {
          'Accept': 'application/json, text/plain, */*',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'Authorization': 'Basic Z2R1LXVhcC11cG1zOmdkdS11YXAtdXBtcw==',
          'Connection': 'keep-alive',
          'Content-Type': 'application/x-www-form-urlencoded',
          'Language': 'zh',
          'Origin': 'http://10.1.254.50:30698',
          'Referer': 'http://10.1.254.50:30698/',
          'TENANT-ID': '1',
          'User-Agent': self.UserAgent,
          'from': 'Y',
          'Cookie': 'token=b9ba9b7d-8b40-405b-9432-99036311ebd2'
        }
        response = requests.request("POST", url, headers=headers, data=payload,verify=False)
        print("登录："+str(response.text))
        res = json.loads(response.content.decode('utf-8'))
        access_token = res["data"]["access_token"]
        #print(access_token)
        return access_token

    def demand(self,access_token,name,date_string):
        '''创建需求'''
        url = self.ziyuan+"/api/business/demand"
        headers = {
          'Accept': 'application/json, text/plain, */*',
          'Authorization': 'Bearer '+access_token,
          'Content-Type': 'application/json;charset=UTF-8',
          'User-Agent': self.UserAgent,
        }
        data={
            'customPointList':[{'latitude':30.4717184,'longitude':114.5377957,'pointDesc':'','pointHeight':60,'pointName':'1','pointType':'POINT','sort':0}],
            'description':'12',
            'executionEndTime':date_string+' 10:55:14',
            'executionStartTime': date_string+' 10:55:14',
            'ifDraft': 'false',
            'level': 3,
            'name': name,
            'natureOfDemand': '1719947187597189128',
            'pointJson': '{\"points\":[{\"name\":\"1\",\"desc\":\"\",\"type\":\"mark\",\"coordinate\":[114.5377957,30.4717184,0]}],\"lines\":[],\"interestPoints\":[],\"polygons\":[]}',
            'position': '',
            'type': 'INCIDENT_RESP'
        }
        response = requests.request("POST", url, headers=headers, json=data,verify=False)
        print("提交需求："+str(response.text))

    def pageInfo(self,access_token,name):
        '''获取任务ID'''
        url = self.omc+"/gdu-la-omc-api/business/work-order/pageInfo"
        headers = {
          'Accept': 'application/json, text/plain, */*',
          'Authorization': 'Bearer '+access_token,
          'Content-Type': 'application/json;charset=UTF-8',
          'User-Agent': self.UserAgent,
        }
        data={
            'name':name,
            'pageNo':1,
            'pageSize':20,
            'source': 2,
            'status': '',
            'statusTab': 0
        }
        response = requests.request("POST", url, headers=headers, json=data,verify=False)
        print("获取任务ID"+str(response.text))
        res = json.loads(response.content.decode('utf-8'))
        id = res["data"]["list"][0]["id"]
        print(id)
        return id

    def assigneeUser(self,access_token,id):
        '''分配飞手'''
        url = self.omc+"/gdu-la-omc-api/business/work-order/assigneeUser"
        headers = {
          'Accept': 'application/json, text/plain, */*',
          'Authorization': 'Bearer '+access_token,
          'Content-Type': 'application/json;charset=UTF-8',
          'User-Agent': self.UserAgent,
        }
        data={
            'workOrderIds':[id],
            'assignUserId':313,
        }
        response = requests.request("PUT", url, headers=headers, json=data,verify=False)
        print("分配飞手："+str(response.text))

    def insert(self,access_token,name,times,sn,trackId):
        '''创建定时任务'''
        url = self.uverurl+"/prod-api/task/task/insert"
        headers = {
          'Accept': 'application/json, text/plain, */*',
          'cookie': 'Tenant-Id=1; token='+access_token,
          'Content-Type': 'application/json;charset=UTF-8',
          'User-Agent': self.UserAgent,
        }
        data={
            'executive':0,
            'nestSn':sn,
            'scheduledTasks':[{'endTime':'','index':'15','nestName':'','nestSn':sn,'startTime':times,'status':2,'taskId':'','taskName':'','trackId':'','trackName':name,'weatherConflict':''}],
            'taskEndTime': times,
            'taskName': name,
            'taskStartTime': '',
            'taskType': 3,
            'trackId': trackId,
            'userId': '',
            'userName': ''
        }
        response = requests.request("POST", url, headers=headers, json=data,verify=False)
        print("创建定时任务："+str(response.text))
        res = json.loads(response.content.decode('utf-8'))
        taskid = res["data"]
        print(taskid)
        return taskid

    def update(self,access_token,id,taskid):
        '''任务关联工单'''
        url = self.work+"/api/work-order-center/update"
        headers = {
          'Accept': 'application/json, text/plain, */*',
          'cookie': 'Tenant-Id=1; token='+access_token,
          'Content-Type': 'application/json;charset=UTF-8',
          'User-Agent': self.UserAgent,
            'authorization':'Bearer '+access_token,
            'host':'10.1.254.50:32243',
            'referer':'http://10.1.254.50:32243/'
        }
        data={
            'id':id,
            'taskIds':[taskid]
        }
        response = requests.request("PUT", url, headers=headers, json=data,verify=False)
        print("任务关联工单："+str(response.text))

    def batch(self,access_token,id,algoId,sceneId):
        '''关联AI算法'''
        url = self.work+"/api/algo/config/save/batch"
        headers = {
          'Accept': 'application/json, text/plain, */*',
          'cookie': 'Tenant-Id=1; token='+access_token,
          'Content-Type': 'application/json;charset=UTF-8',
          'User-Agent': self.UserAgent,
            'authorization':'Bearer '+access_token,
            'host':'10.1.254.50:32243',
            'referer':'http://10.1.254.50:32243/'
        }
        data={
            'taskAlgoSaveReqs':[{"taskId":id,"algoId":algoId,"sceneId":sceneId,"paramJson":"{}","areaInfoList":[]}],
            'taskId':id
        }
        response = requests.request("POST", url, headers=headers, json=data,verify=False)
        print("关联AI算法："+str(response.text))

    def confirmExecute(self,access_token,id):
        '''确认实施'''
        url = self.work+"/api/work-order-center/confirmExecute"
        headers = {
          'Accept': 'application/json, text/plain, */*',
          'cookie': 'Tenant-Id=1; token='+access_token,
          'Content-Type': 'application/json;charset=UTF-8',
          'User-Agent': self.UserAgent,
            'authorization':'Bearer '+access_token,
            'host':'10.1.254.50:32243',
            'referer':'http://10.1.254.50:32243/'
        }
        data={
            'id':id,
            'approve':1
        }
        response = requests.request("PUT", url, headers=headers, json=data,verify=False)
        print("确认实施："+str(response.text))



if __name__ == '__main__':
    ##管理员账号登录
    access_token = task().login('jzhuanghui', 'S3nFbGk/HNI=')
    now = time.time()
    name='警情'+str(int(now))
    print(name)
    current_time=time.localtime()
    date_string=time.strftime("%Y-%m-%d",current_time)
    ##资源共享系统提交需求
    task().demand(access_token,name,date_string)
    time.sleep(5)
    ##运行管理系统获取任务ID
    id=task().pageInfo(access_token,name)
    ##运行管理系统分派飞手
    task().assigneeUser(access_token,id)
    ##飞手账号登录
    access_token = task().login('JIN1', 'S3nFbGk/HNI=')
    now=datetime.now()
    new=now+timedelta(minutes=60)  ##定时任务执行时间，X分钟后执行
    times=int(new.timestamp())*1000
    time.sleep(5)
    ##工单中心创建定时任务-关联工单
    taskid=task().insert(access_token,name,times,'CGDJKK1B23KDG0042','141391571926259')
    time.sleep(5)
    task().update(access_token,id,taskid)
    time.sleep(5)
    ##工单中心关联AI算法
    task().batch(access_token, id,'pfw1.3','28')
    time.sleep(5)
    ##工单中心确认实施
    time.sleep(5)
    task().confirmExecute(access_token,id)


